package com.yoomiito.app.ui.order.sureorder.singleGoods

import android.text.TextUtils
import cn.droidlover.xdroidmvp.net.ApiException
import cn.droidlover.xdroidmvp.net.ApiSubscriber
import cn.droidlover.xdroidmvp.net.BaseModel
import cn.droidlover.xdroidmvp.net.XApi
import com.alibaba.fastjson.JSONObject
import com.yoomiito.app.base.AppConfig
import com.yoomiito.app.base.BaseActPresenter
import com.yoomiito.app.model.bean.AddressInfo
import com.yoomiito.app.model.my.MyRemainMoneyInfo
import com.yoomiito.app.model.order.CreateOrderInfo
import com.yoomiito.app.model.order.NewCreateOrderData
import com.yoomiito.app.model.sdd.SddFreeGoodsData
import com.yoomiito.app.net.YmApi
import com.yoomiito.app.pay.OrderPayInfo
import com.yoomiito.app.showToast
import com.yoomiito.app.utils.*
import okhttp3.RequestBody
import java.util.*

class NewSureOrderPresenter(appConfig: AppConfig) : BaseActPresenter<NewSureOrderActivity>(appConfig) {

    //送多多-赠品创建订单
    fun createSddOrder(data: NewCreateOrderData) {
        L.i("param:\n" +
                "\nconsignee=${data.addressInfo.userName}" +
                "\narea_id=${data.addressInfo.provinceCode}" +
                "\narea_id2=${data.addressInfo.cityCode}" +
                "\narea_id3=${data.addressInfo.countyCode}" +
                "\narea_name=${data.addressInfo.areaName}" +
                "\nmobile=${data.addressInfo.mobile}" +
                "\naddress=${data.addressInfo.address}" +
                "\nnote=${data.goodsInfo[0].notes}" +
                "\nproduct_id=${data.goodsInfo[0].product_id}")
        YmApi.getYmService()
                .sddFreeGoodsCreateOrder(
                        data.addressInfo.userName,
                        data.addressInfo.provinceCode,
                        data.addressInfo.cityCode,
                        data.addressInfo.countyCode,
                        data.addressInfo.areaName,
                        data.addressInfo.mobile,
                        data.addressInfo.address,
                        data.goodsInfo[0].notes,
                        data.goodsInfo[0].product_id.toString()
                )
                .compose(v.bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<SddFreeGoodsData>() {
                    override fun onSuccess(t: SddFreeGoodsData?) {
                        v.dismissLoading()
                        t?.let { v.createOrderSuccess(t) }

                    }

                    override fun onFail(error: ApiException?) {
                        v.dismissLoading()
                        error?.msg?.showToast()
                    }

                })
    }

    //    fun createOrder(productId: String, consignee: String, provinceId: String,
//                    cityId: String, countryId: String, areaName: String, tel: String, address: String, note: String, num: String) {
    fun createOrder(data: NewCreateOrderData) {
        val params = LinkedHashMap<String, String>()
        params["product_id"] = data.goodsInfo[0].product_id.toString()
        params["consignee"] = data.addressInfo.userName
        params["area_id"] = data.addressInfo.provinceCode
        params["area_id2"] = data.addressInfo.cityCode
        params["area_id3"] = data.addressInfo.countyCode
        params["area_name"] = data.addressInfo.areaName
        params["mobile"] = data.addressInfo.mobile
        params["address"] = data.addressInfo.address
        params["note"] = data.goodsInfo[0].notes
        params["num"] = data.goodsInfo[0].num.toString()
        val body = RequestBody.create(YmApi.JSON, JSONObject.toJSONString(params))
        YmApi.getYmService().createOrder(body)
                .compose(v.bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<CreateOrderInfo>(handleException()) {
                    override fun onSuccess(t: CreateOrderInfo?) {
                        getPayInfo(t!!)
                    }

                    override fun onFail(error: ApiException?) {
                        v.dismissLoading()
                    }

                })
    }

    private fun getPayInfo(info: CreateOrderInfo) {
        YmApi.getYmService().moneyAgent
                .compose(v.bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<MyRemainMoneyInfo>(handleException()) {
                    override fun onSuccess(t: MyRemainMoneyInfo?) {
                        t?.let { v.pay(OrderPayInfo(info, it)) }

                    }

                    override fun onFail(error: ApiException?) {
                        if (hasV()) {
                            v.dismissLoading()
                        }
                    }
                })
    }

    fun getRemain() {
        YmApi.getYmService()
                .moneyAgent
                .compose(v.bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<MyRemainMoneyInfo>(handleException()) {
                    override fun onSuccess(data: MyRemainMoneyInfo) {
                        v.dismissLoading()
//                        data.isShowYoumi = true
//                        v.setYouMi(data)
                        //                        getV().orderId = orderResult.getOut_trade_no();
//                        PayTypeUtils.wxPay(orderResult);
                    }

                    override fun onFail(error: ApiException) {
                        v.dismissLoading()
                        YMToast.showText("优米数量获取失败 请稍后再试")
                        v.finish()
                    }
                })
    }

    fun getAddress() {
        YmApi.getYmService()
                .defaultAddress
                .compose(v.bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<AddressInfo>() {
                    override fun onSuccess(addressInfo: AddressInfo) {
                        v.showAddressView(addressInfo)
                    }

                    override fun onFail(error: ApiException) {
                        v.dismissLoading()
                        if (!TextUtils.isEmpty(error.msg)) {
                            YMToast.showText(error.msg)
                        }
                    }
                })
    }

    fun queryOrder(orderId: String, pay_type: String) {
        val eventMessage = EventMessage()
        YmApi.getYmService()
                .quseryOrderStatus(orderId, pay_type)
                .compose(v.bindToLifecycle())
                .compose(XApi.getApiTransformerNoData<BaseModel<*>>())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<BaseModel<*>?>(handleException()) {
                    override fun onSuccess(baseModel: BaseModel<*>?) {
                        if (v == null) return
//                        eventMessage.code = Type.EventMsgType.
//                        v.payResult(eventMessage)
                    }

                    override fun onFail(error: ApiException) {
                        if (v == null) return
//                        eventMessage.code = AllCode.Fail
//                        v.payResult(eventMessage)
                    }
                })
    }
}